package org.youchan.util;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class MessagingQueue<M> {
	private MessageHandler<M> mHandler;
	private BlockingQueue<M> mQueue;
	private boolean mRunning;
	
	public MessagingQueue(MessageHandler<M> handler) {
		mHandler = handler;
		mQueue = new ArrayBlockingQueue<M>(100);
	}
	
	public void sendMessage(M message) {
		try {
			mQueue.put(message);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void start() {
		mRunning = true;
		new Thread() {
			public void run() {
				try {
					while (mRunning) {
						M message = mQueue.take();
						mHandler.handle(message);
					}
				} catch (InterruptedException e) {
					mRunning = false;
				} catch (Exception e) {
					Exception e2 = new Exception("exception occurs in MessageHandler", e);
					e2.printStackTrace();
				}
			}
		}.start();
	}
	
	public void stop() {
		mRunning = false;
	}
}
